﻿using System;

using System.Collections.Generic;
using System.Text;
using Silvermoon.UI;
using Silvermoon.Windows;

namespace Silvermoon.Controls.Base
{
    /// <summary>
    /// Base class for all buttons which support IsChecked.
    /// </summary>
    public class ToggleButtonBase : ButtonBase
    {
        #region commands

        public static readonly Command CheckBoxCommand = new Command();

        #endregion
        #region props

        /// <summary>
        /// Gets or sets whether the button is checked.
        /// </summary>
        public bool IsChecked
        {
            get { return (bitmask & 2) != 0; }
            set
            {
                if (value != IsChecked)
                {
                    bitmask = (ushort)(value ? bitmask | 2 : bitmask & ~2);
                    OnCheckedChanged();
                }
            }
        }

        #endregion
        #region methods

        public override void PreInitialize()
        {
            base.PreInitialize();
            SetState(IsChecked ? VState.Checked : VState.Unchecked);
        }

        protected virtual void OnCheckedChanged()
        {
            bool isChecked = IsChecked;
            SetState(isChecked ? VState.Checked : VState.Unchecked);
            if (CheckedChanged != null) CheckedChanged(this, EventArgs.Empty);
            Invalidate(InvalidationFlag.Appearance);
            if (Command != null) RaiseCommand(Command);
        }

        protected override void RaiseButtonCommand()
        {
        }

        protected internal override void OnTap(TapEventArgs e)
        {
            OnToggleButtonTap(e);
            base.OnTap(e);
        }

        protected virtual void OnToggleButtonTap(TapEventArgs e)
        {
            if (!e.Handled)
            {
                e.Handled = true;
                if (Enabled) IsChecked ^= true;
            }
        }

        #endregion
        #region events

        public event EventHandler CheckedChanged;

        #endregion
    }
}
